package com.itjin.controller;

import com.itjin.model.domain.dto.CourseScheduleUploadDTO;
import com.itjin.model.domain.dto.CourseCreateDTO;
import com.itjin.model.domain.dto.CourseEditDTO;
import com.itjin.model.domain.entity.Course;
import com.itjin.model.domain.vo.CourseDetailVO;
import com.itjin.model.result.Result;
import com.itjin.service.CourseScheduleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 课程表相关接口
 */
@Tag(name = "课程表管理", description = "课程表相关功能接口")
@RestController
@RequestMapping("/api/course-schedule")
@Slf4j
public class CourseScheduleController {

    @Autowired
    private CourseScheduleService courseScheduleService;

    /**
     * 上传并解析课程表图片
     */
    @PostMapping("/upload-image")
    @Operation(summary = "上传课程表图片进行OCR解析")
    public Result<List<Course>> uploadScheduleImage(@Valid @RequestBody CourseScheduleUploadDTO uploadDTO) {
        try {
            log.info("接收到课程表图片上传请求，用户ID：{}，图片URL：{}", uploadDTO.getUserId(), uploadDTO.getImageUrl());
            
            // 调用OCR识别服务
            List<Course> courses = courseScheduleService.parseScheduleFromImage(
                uploadDTO.getUserId(), 
                uploadDTO.getImageUrl()
            );
            
            if (courses.isEmpty()) {
                return Result.failure(400, "未能从图片中识别出课程信息，请检查图片质量或手动添加课程");
            }
            
            // 保存课程信息
            int savedCount = courseScheduleService.saveCourses(courses);
            log.info("成功保存{}门课程", savedCount);
            
            return Result.success(courses);
            
        } catch (Exception e) {
            log.error("课程表图片解析失败：", e);
            return Result.failure(500, "课程表解析失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户指定周的课程表
     */
    @GetMapping("/weekly")
    @Operation(summary = "获取用户指定周的课程表")
    public Result<Object> getUserWeeklySchedule(
            @Parameter(description = "用户ID", required = true) @RequestParam("userId") Integer userId,
            @Parameter(description = "第几周", required = true) @RequestParam("week") Integer week) {
        
        try {
            log.info("获取用户{}第{}周的课程表", userId, week);
            
            Object weeklySchedule = courseScheduleService.getUserWeeklySchedule(userId, week);
            
            return Result.success(weeklySchedule);
            
        } catch (Exception e) {
            log.error("获取用户课程表失败：", e);
            return Result.failure(500, "获取课程表失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户当前周的课程表（默认第1周）
     */
    @GetMapping("/current")
    @Operation(summary = "获取用户当前周的课程表")
    public Result<Object> getCurrentWeekSchedule(
            @Parameter(description = "用户ID", required = true) @RequestParam("userId") Integer userId) {
        
        try {
            // 这里可以根据实际需求计算当前是第几周，暂时默认为第1周
            Integer currentWeek = 1;
            
            Object weeklySchedule = courseScheduleService.getUserWeeklySchedule(userId, currentWeek);
            
            return Result.success(weeklySchedule);
            
        } catch (Exception e) {
            log.error("获取用户当前周课程表失败：", e);
            return Result.failure(500, "获取当前周课程表失败：" + e.getMessage());
        }
    }

    /**
     * 获取课程详情
     */
    @GetMapping("/{courseId}")
    @Operation(summary = "获取课程详情")
    public Result<CourseDetailVO> getCourseDetail(
            @Parameter(description = "课程ID", required = true) @PathVariable("courseId") Integer courseId) {
        
        try {
            log.info("获取课程详情，课程ID：{}", courseId);
            
            CourseDetailVO courseDetail = courseScheduleService.getCourseDetail(courseId);
            
            return Result.success(courseDetail);
            
        } catch (Exception e) {
            log.error("获取课程详情失败：", e);
            return Result.failure(500, "获取课程详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增课程
     */
    @PostMapping("/create")
    @Operation(summary = "新增课程")
    public Result<CourseDetailVO> createCourse(@Valid @RequestBody CourseCreateDTO courseCreateDTO) {
        try {
            log.info("新增课程，用户ID：{}，课程名称：{}", courseCreateDTO.getUserId(), courseCreateDTO.getCourseName());
            
            CourseDetailVO courseDetail = courseScheduleService.createCourse(courseCreateDTO);
            
            return Result.success(courseDetail);
            
        } catch (Exception e) {
            log.error("新增课程失败：", e);
            return Result.failure(500, "新增课程失败：" + e.getMessage());
        }
    }

    /**
     * 编辑课程
     */
    @PutMapping("/edit")
    @Operation(summary = "编辑课程")
    public Result<CourseDetailVO> editCourse(@Valid @RequestBody CourseEditDTO courseEditDTO) {
        try {
            log.info("编辑课程，课程ID：{}，课程名称：{}", courseEditDTO.getId(), courseEditDTO.getCourseName());
            
            CourseDetailVO courseDetail = courseScheduleService.editCourse(courseEditDTO);
            
            return Result.success(courseDetail);
            
        } catch (Exception e) {
            log.error("编辑课程失败：", e);
            return Result.failure(500, "编辑课程失败：" + e.getMessage());
        }
    }

    /**
     * 删除课程
     */
    @DeleteMapping("/{courseId}")
    @Operation(summary = "删除课程")
    public Result<Boolean> deleteCourse(
            @Parameter(description = "课程ID", required = true) @PathVariable("courseId") Integer courseId) {
        
        try {
            log.info("删除课程，课程ID：{}", courseId);
            
            boolean success = courseScheduleService.deleteCourse(courseId);
            
            return Result.success(success);
            
        } catch (Exception e) {
            log.error("删除课程失败：", e);
            return Result.failure(500, "删除课程失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户所有课程列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取用户所有课程列表")
    public Result<List<CourseDetailVO>> getUserCourses(
            @Parameter(description = "用户ID", required = true) @RequestParam("userId") Integer userId) {
        
        try {
            log.info("获取用户课程列表，用户ID：{}", userId);
            
            List<CourseDetailVO> courses = courseScheduleService.getUserCourses(userId);
            
            return Result.success(courses);
            
        } catch (Exception e) {
            log.error("获取用户课程列表失败：", e);
            return Result.failure(500, "获取用户课程列表失败：" + e.getMessage());
        }
    }

} 